package com.mzm.config;

import java.io.InputStream;

import org.apache.commons.lang.math.RandomUtils;
import org.joda.time.base.BaseDateTime;

import com.thoughtworks.xstream.XStream;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class ConfigurationServiceImpl implements ConfigurationService {

	private static XStream xStream;
	static {
		xStream = new XStream();
		xStream.omitField(BaseDateTime.class, "iChronology");
	}

	private ConfigDao configDao;

	public void setConfigDao(ConfigDao configDao) {
		this.configDao = configDao;
	}

	@Override
	public Parameter getParameter(String section, String paramName) {
		return configDao.getParam(section, paramName);
	}

	@Override
	public Object getObjectParameter(String section, String paramName) {
		Parameter parameter = getParameter(section, paramName);
		if (parameter == null) {
			return null;
		}
		return parameter.getObjectValue();
	}

	@Override
	public String getDbVersion() {
		return configDao.getParam("db", "version").getStringValue();
	}

	@Override
	public void setParameter(String section, String paramName, String value) {
		Parameter parameter = new Parameter(section, paramName, value);
		setParameterImpl(parameter);
	}

	public void setParameterImpl(Parameter p) {
		Parameter parameter = getParameter(p.getSection(), p.getName());
		if (parameter == null) {
			parameter = p;
			int id = RandomUtils.nextInt();
			for (int i = 3; i < 100; i++) {
				if (configDao.findById(i, false) == null) {
					id = i;
					break;
				}
			}
			parameter.setId(id);
		} else {
			parameter.setValue(p.getValue());
		}
		configDao.createOrUpdate(parameter);
	}

	@Override
	public void setParameter(String section, String paramName, Object value) {
		Parameter parameter = new Parameter(section, paramName);
		parameter.setValue(value);
		setParameterImpl(parameter);
	}

	@Override
	public Object loadConfigObjectFromStream(InputStream is) {
		if (is == null) {
			return null;
		}
		return xStream.fromXML(is);
	}

}
